#!/usr/bin/python



from xpcom import components

import logging
logger = logging.getLogger("event_handler")



############################################################

class EventHandler:
	
	_com_interfaces_ = [components.interfaces.nsIEventHandlers]
	_reg_clsid_ = "{4f44d845-dc20-4b1c-a954-cf3e9b270830}"
	_reg_contractid_ = "@mozilla.org/EventHandlers;1"

############################################################

	def __init__(self):
		
		self.tags_synchronizer = components.classes["@mozilla.org/TagsSynchronizer;1"].getService(components.interfaces.nsITagsSynchronizer)

############################################################

	def importXulConstants(self):
		
		self.PATH_MAIN = components.classes['@mozilla.org/file/directory_service;1'].getService(components.interfaces.nsIProperties).get("ProfD", components.interfaces.nsILocalFile).path
		self.PATH_CONTENT = self.PATH_MAIN + "/extensions/nepomukfoxtrot@nepomuk.semanticdesktop.org/chrome/content/"
		import sys
		sys.path.append(self.PATH_CONTENT)
		import xul_constants

############################################################

	def saveRating(self, page_uri, rateNum, document, window=None):
		
		logger.debug("saveRating() in the position")
		
		self.importXulConstants()
		import dbus
		from constants import PIMO_GROUNDINGOCCURRENCE, NFO_WEBSITE
		from pyfuncs import getRealPageTitle
		
		from the_nepomuk_whisperer import TheNepomukWhisperer
		nepo = None
		try:
			nepo = TheNepomukWhisperer()
		except dbus.exceptions.DBusException, e:
			# PROMPTS.alert(window, "Error", "It seems that org.kde.NepomukStorage service is not accessible. Maybe nepomukserver is not or badly running?")
			logger.debug("Error instanciating TheNepomukWhisperer: %s" % e)
			return 1
		
		document_uri = nepo.interface.getAntecedent(PIMO_GROUNDINGOCCURRENCE, page_uri)
		if document_uri != None:
			logger.debug("The document %s has %s as its groundingOccurrence." % (document_uri, page_uri))
		else:
			logger.debug("The page \"%s\" has no groundingOccurrence, creating one." % page_uri)
			document_uri = nepo.interface.registerAndReify(page_uri, NFO_WEBSITE, getRealPageTitle(window.title))
		
		nepo.nao.setNumericRating(document_uri, rateNum)

############################################################

	def rmComment(self, page_uri, document):
		
		print "rmComment in the position"
		
		self.importXulConstants()
		import dbus
		from constants import PIMO_GROUNDINGOCCURRENCE
		
		from the_nepomuk_whisperer import TheNepomukWhisperer
		nepo = None
		try:
			nepo = TheNepomukWhisperer()
		except dbus.exceptions.DBusException, e:
			# PROMPTS.alert(window, "Error", "It seems that org.kde.NepomukStorage service is not accessible. Maybe nepomukserver is not or badly running?")
			logger.debug("Error instanciating TheNepomukWhisperer: %s" % e)
			return 1
		
		
		document_uri = nepo.interface.getAntecedent(PIMO_GROUNDINGOCCURRENCE, page_uri)
		if document_uri != None:
			logger.debug("The document %s has %s as its groundingOccurrence." % (document_uri, page_uri))
		else:
			return 1
		
		nepo.nao.removeDescription(document_uri)

############################################################

	def refreshPageInfo(self, page_uri, document):
		
		if page_uri == None: # It seems to happen sometimes, for example after adding a bookmark.
			logger.debug("refreshPageInfo() called with page_uri == None...")
			return 1
		
		logger.debug("refreshPageInfo() in the position")
		
		self.importXulConstants()
		import dbus
		from constants import PIMO_GROUNDINGOCCURRENCE
		
		from the_nepomuk_whisperer import TheNepomukWhisperer
		nepo = None
		try:
			nepo = TheNepomukWhisperer()
		except dbus.exceptions.DBusException, e:
			# PROMPTS.alert(window, "Error", "It seems that org.kde.NepomukStorage service is not accessible. Maybe nepomukserver is not or badly running?")
			logger.debug("Error instanciating TheNepomukWhisperer: %s" % e)
			return 1
		
		
		commentText = "no description"
		rateNum = 0
		
		document_uri = nepo.interface.getAntecedent(PIMO_GROUNDINGOCCURRENCE, page_uri)
		if document_uri != None:
			logger.debug("The document %s has %s as its groundingOccurrence." % (document_uri, page_uri))
			commentText = nepo.nao.getDescriptionOf(document_uri) # get the comment of current page
			rateNum = nepo.nao.getNumericRating(document_uri) # get the rate number
    
		logger.debug("commentText = %s ; rateNum = %s" % (commentText, rateNum))
		#Set the comment to the tiptext of image
		if commentText == "no description":
			document.getElementById("commentIcon").setAttribute("src", "chrome://nepomuk/content/images/writeDesc.png")
		else:
			document.getElementById("commentIcon").setAttribute("src", "chrome://nepomuk/content/images/comment.png")
		document.getElementById("commentIcon").setAttribute("tooltiptext", commentText)
		
		#Set the rate number to the tiptext of label
		document.getElementById("rateLabel").setAttribute("tooltiptext", str(rateNum))
		
		# Set the light stars
		for i in range(10):
			
			starFileName = "star"
			
			if i < rateNum:
				starFileName += "Light"
			else:
				starFileName += "Dark"
			
			if i % 2 == 0:
				starFileName += "L"
			else:
				starFileName += "R"
			
			starId = "star%s" % i
			document.getElementById(starId).setAttribute('src', 'chrome://nepomuk/content/images/%s.png' % starFileName)

############################################################

	def placesItemChanged(self, aBookmarkId, aProperty, aIsAnnotationProperty, aValue):
		
		bmsvc = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"].getService(components.interfaces.nsINavBookmarksService)
		
		logger.debug("tagItemChanged():")
		logger.debug("\taBookmarkId = %s" % aBookmarkId)
		logger.debug("\taProperty = %s" % aProperty)
		logger.debug("\taIsAnnotationProperty = %s" % aIsAnnotationProperty)
		logger.debug("\taValue = %s" % aValue)
		
		logger.debug("\ttag:")
		title = bmsvc.getItemTitle(aBookmarkId)
		logger.debug("\t\ttitle = %s" % title)
		uri = bmsvc.getBookmarkURI(aBookmarkId)
		logger.debug("\t\turi = %s" % uri)

############################################################

	def placesItemRemoved(self, aItemId, aFolder, aIndex):
		
		logger.debug("itemRemoved(%s, %s, %s)" % (aItemId, aFolder, aIndex))
		
		# remove tag from nepomuk as well
		self.tags_synchronizer.synchronize("None", "False")

############################################################

	def placesItemAdded(self, aItemId, aFolder, aIndex):
		
		logger.debug("itemAdded(%s, %s, %s)" % (aItemId, aFolder, aIndex))
		
		# add tag in nepomuk as well
		self.tags_synchronizer.synchronize("True", "None")








